import axios from 'axios'

export default {
    namespaced: true,
    state: {
        books:[] // 初始数据
    },
    mutations: {
        updateBooks: function (state, newBooks) {
            state.books = newBooks
        }
    },
    getters: {
        'totalMoney':function(state){
            // console.log(state);
            // const totalMoney = 10000+ state.books[0].price + state.books[1].price +state.books[2].price 
            // const totalMoney = state.books.reduce((sum,item)=>sum+= item.price, 0)
            // return totalMoney

            return state.books.reduce((sum,item) => sum+item.price, 0)
        }
    },
    actions:{
        'getBooks': function(context) {
            // 1. 发异步请求
            axios({
                url: 'https://www.fastmock.site/mock/37d3b9f13a48d528a9339fbed1b81bd5/book/api/books',
                method: 'GET'
            }).then(res => {
             // 2. 保存数据到vuex
             context.commit('updateBooks', res.data.data)
 
            })
        }
    }
}